package com.cyj.qqclient.service;

import com.cyj.qqcommon.Message;
import com.cyj.qqcommon.MessageType;
import com.cyj.qqcommon.User;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * 校验用户是否存在
 */
public class UserClientService implements Serializable {
    private User user= new User();
    private Socket socket;

    public boolean checkUser(String username, String password){
        boolean flag=false;
        user.setUserid(username);
        user.setUserpassword(password);

        try {
            socket = new Socket(InetAddress.getByName("192.168.173.188"),9999);
            //得到传输对象
            ObjectOutputStream oos= new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(user);//发送User对象

            ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());//读取服务器发送的Message对象
            Message ms=(Message)ois.readObject();

            if(ms.getMessageType().equals(MessageType.MESSAGE_LOGIN_SUCCEED)){
                //创建一个和服务器端保持通信的线程 ->ClientConnectServerThread
                ClientConnectServerThread ccst = new ClientConnectServerThread(socket);//启动线程
                ccst.start();
                //将线程放入集合
                ManageClientConnectSeverThread.addClientConnectServerThread(username,ccst);
                flag=true;
            }else{
                System.out.println("登录失败");
                socket.close();
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        return flag;
    }

    //向服务器请求在线用户列表
    public void onlineFriendList(){
        Message message=new Message();//发送MESSAGE_GET_....
        message.setMessageType(MessageType.MESSAGE_GET_ONLINE_FRIEND);
        message.setSender(user.getUserid());
        try {
            ObjectOutputStream oos =
                    new ObjectOutputStream(ManageClientConnectSeverThread.getClientConnectServerThread(user.getUserid()).getSocket().getOutputStream());
            oos.writeObject(message);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    //退出客户端，向服务端发送退出message
    public void exitUserClient(){
        Message message=new Message();
        message.setMessageType(MessageType.MESSAGE_CLIENT_EXIT);
        message.setSender(user.getUserid());
        try {
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            objectOutputStream.writeObject(message);
            System.exit(0);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}
